<template>
  <view class="video">
    <!-- 顶部导航栏 90upx-->
    <nav-back>
      <view class="navBar">
        <scroll-view class="scrollView" scroll-x scroll-with-animation>
          <view class="gameNav">
            <view class="gameNavItem" :class="index === currentTab ? 'gameNavItemActive' : ''" v-for="(item, index) in tabs" :key="index" @tap="tabSelect(index)">
              <text class="gameNavItemText">{{ item }}</text>
            </view>
          </view>
        </scroll-view>
        <navigator url="/pages/uCenter/gameRecord" class="navigator">助威记录</navigator>
      </view>
    </nav-back>

    <view class="swiper">
      <history v-if="currentTab === 0"></history>
      <view v-if="currentTab === 1" class="live">
        <!-- 直播列表导航条 80upx -->
        <scroll-view scroll-x 
        class="liveNav text-center bg-black" 
        :scroll-left="liveScrollLeft" 
        scroll-with-animation
        v-if="STATE.video.lives.length > 0 && currentTab === 1">
          <view
            class="liveNav-item"
            :class="index == STATE.video.currentLive ? 'active' : ''"
            v-for="(item, index) in STATE.video.lives"
            :key="index"
            :data-index="index"
            @click="liveTabSelect(index)"
          >
            <text>{{ item.teamAName }} vs {{ item.teamBName }}</text>
          </view>
        </scroll-view>

        <!-- 视频播放器 400upx-->
        <view class="videoPlayer" v-if="currentLiveInfo">
          <video id="video" :src="currentLiveInfo.url" :direction="-90" danmu-btn enable-danmu controls autoplay></video>
        </view>
        <!-- 人气 25upx-->
        <popularity :teamAPeoples="support ? support.teamAPeoples : 0" :teamBPeoples="support ? support.teamAPeoples : 0"></popularity>

        <!-- 积分 106upx -->
        <score bg-color="#ffffff" :teamAScore="support ? support.teamASupport : 0" :teamBScore="support ? support.teamBSupport : 0"></score>

        <view style="margin-top: -20upx;z-index: 0;">
          <!-- 助威 80upx - 20upx-->
          <cheer
            v-if="currentLiveInfo && currentLiveInfo.odds[0]"
            :oddIds="currentLiveInfo.oddIds"
            :teamAName="currentLiveInfo.teamAName"
            :teamAData="{ name: currentLiveInfo.teamAName, odd: currentLiveInfo.odds[0] }"
            :teamBName="currentLiveInfo.teamBName"
            :teamAScore="currentLiveInfo.teamAScore"
            :teamBScore="currentLiveInfo.teamBScore"
            :teamBData="{ name: currentLiveInfo.teamBName, odd: currentLiveInfo.odds[1] }"
            @event-change="onCheerChange"
            :moreUrl="'/pages/video/moreGameType?type=more&id=' + currentLiveInfo.id"
          ></cheer>
        </view>
        <!-- 群聊框 100% - 70upx - 400upx -94upx - 120upx -->
        <view class="chat" :style="'height: calc(100% - 70upx - 400upx - 25upx - 106upx - 60upx);'"><chat></chat></view>
      </view>

      <notice v-if="currentTab === 2"></notice>
    </view>
    <cheer-modal
      :show.sync="liveCherrModalShow"
      v-if="currentLiveInfo && liveSelectOdd"
      :cheerTitle="'在' + currentLiveInfo.matchName + ' 中 ' + currentLiveInfo.teamAName + ' VS ' + currentLiveInfo.teamBName + ' 的比赛,您认为'"
      :cheerDesc="liveSelectTeam + ' 胜'"
      @event-submit="onSubmitCheer"
      :odd="liveSelectOdd"
    ></cheer-modal>
  </view>
</template>
<script>
import navBack from "@/components/navBack";

import history from "./components/history";
import notice from "./components/notice";
// 积分
import score from "./components/score";
// 人气
import popularity from "./components/popularity";
// 助威
import cheer from "@/components/cheer";
import chat from "@/components/chat/index";
import cheerModal from "@/components/cheer/modal";
import uniApp from "@/utils/uni-app";
let roomId, video, timer, supportTimer;
export default {
  components: {
    navBack,
    history,
    notice,
    score,
    popularity,
    cheer,
    chat,
    cheerModal
  },
  data() {
    return {
      currentTab: 1,
      tabs: ["往期赛果", "热门直播", "赛程预告"],

      chatHeight: 0,
      //直播数据
      liveScrollLeft: 0,
      liveCherrModalShow: false,
      liveSelectTeam: null,
      liveSelectOdd: {},

      support: null
    };
  },
  computed: {
    // 当前直播的信息
    currentLiveInfo() {
      return this.$store.state.video.lives[this.$store.state.video.currentLive];
    }
  },
  onShow() {
    getApp().globalData.socket.initSocket();
    // 定时获取积分和人气
    // supportTimer = setInterval(() => {
    //   this.getMatchSupportDetail();
    // }, 5000);
  },
  onHide() {
    clearInterval(supportTimer);
    clearInterval(timer);
  },
  // bar 切换栏目
  onLoad(options) {
    this.current = options.current || 1;
    roomId = options.roomId ? parseInt(options.roomId) : null;
    if (this.current === 1) {
      this.initLive();
      // 定时刷新
      // this.intervalRefreshLive();
    }
    // 接收到弹幕
    uni.$on("live_danmu", data => {
      console.log("%c [弹幕] %c 监听到弹幕", "color:blue", "color:#000", data);
      video.sendDanmu(data.data.message);
    });
    // #ifdef H5
    window.addEventListener("beforeunload", () => {
      this.$store.dispatch("video/leaveLiveRoom", this.currentLiveInfo.id);
    });
    // #endif
    
    video = uni.createVideoContext("video", this);
    
    
  },
  onPullDownRefresh() {
    if (this.currentTab === 1) {
      let p1 = this.$store.dispatch("setting/getConfig");
      let p2 = this.$store.dispatch("video/getLives");
      Promise.all([p1, p2]).then(_ => {
        uni.stopPullDownRefresh();
      });
    }
    uni.$emit("video_onPullDownRefresh");
  },
  methods: {
    getMatchSupportDetail() {
      return this.$api.video.getMatchSupportDetail(this.currentLiveInfo.id).then(_ => {
        this.support = _.data.data;
        return _.data.data;
      });
    },
    tabSelect(current) {
      this.currentTab = current;
      if (current === 1) {
        this.intervalRefreshLive();
        roomId = this.$store.state.video.lives[this.$store.state.video.currentLive].id;
        this.$store.commit("video/CHANGE_ROOM", 100);
        this.$store.commit("video/CHANGE_ROOM", this.$store.state.video.currentLive);
        this.initLive();
      } else {
        clearInterval(timer);
        clearInterval(supportTimer);
      }
    },
    // -----live begin------
    // intervalRefreshLive() {
    //   timer = setInterval(() => {
    //     this.$store.dispatch("setting/getConfig");
    //     this.$store.dispatch("video/getLives");
    //   }, 5000);
    // },
    initLive() {
      this.$store.dispatch("setting/getConfig");
      return this.$store.dispatch("video/getLives").then(response => {
        if (roomId) {
          for (let i = 0; i < response.data.data.length; i++) {
            if (response.data.data[i].id !== roomId) continue;
            this.$store.commit("video/CHANGE_ROOM", i);
            break;
          }
        } else {
          this.$store.commit("video/CHANGE_ROOM", 0);
        }
        this.$store.dispatch("video/changeLiveRoom");
        this.getMatchSupportDetail();
        return response;
      });
    },
    // 切换直播间
    liveTabSelect(current) {
      this.liveScrollLeft = (current - 1) * 120;
      roomId = this.$store.state.video.lives[this.$store.state.video.currentLive].id;
      // 离开当前房间
      this.$store.dispatch("video/leaveLiveRoom", roomId);
      this.$store.commit("video/CHANGE_ROOM", current);

      // 切换房间
      this.$store.dispatch("video/changeLiveRoom").then(_ => {
        uni.$emit("scoreVs_init");
      });
      roomId = this.$store.state.video.lives[this.$store.state.video.currentLive].id;
    },
    // 事件委托 切换直播间
    onClickLive(e){
      console.warn(e)
    },
    
    
    
    // 监听助威改变
    onCheerChange(e) {
      this.liveSelectTeam = e.name;
      this.liveSelectOdd = e.odd;
      this.liveCherrModalShow = true;
    },
    onSubmitCheer(e) {
      this.$api.video
        .postCheer({
          oddId: e.oddId,
          flower: e.flowerTotal,
          useDebt: e.isUseWhiteStrip ? 1 : 0
        })
        .then(response => {
          uniApp.toast("助威成功");
          setTimeout(() => {
            this.initLive();
          }, 2000);
        })
        .catch(e => {
          uniApp.alert(e.message || e.data.msg || "助威失败");
        });
    }
  },
  onUnload() {
    // 监听弹幕卸载
    console.log("%c [弹幕] %c 关闭弹幕监听", "color:blue", "color:#000");
    uni.$off("live_danmu");
    
    clearInterval(supportTimer);
    // 退出房间
    this.$store.dispatch("video/leaveLiveRoom", this.currentLiveInfo.id);
    // 清除定时刷新数据计时器
    clearInterval(timer);
    if (this.$store.state.setting.IS_OPEN_BG_MUSIC) {
      const bgAudioManager = uni.getBackgroundAudioManager();
      bgAudioManager.play();
    }
  }
};
</script>

<style lang="scss" scoped>
  .navBar {
    /* #ifndef APP-PLUS-NVUE */
    display: flex;
    /* #endif */
    flex-direction: row;
    justify-content: space-between;
    align-items: center;
    width: 100%;
  }
  .navigator {
    width: 160rpx;
    color: yellow;
    text-decoration: underline;
  }
.gameNav {
  height: 90rpx;
  /* #ifndef APP-PLUS-NVUE */
  display: flex;
  /* #endif */
  flex-direction: row;
  align-items: center;
}
.gameNavItem {
  margin: 0 20rpx;
}
.gameNavItemActive {
  border-bottom: 5rpx solid #ffffff;
  transform: scale(1.2);
}
.gameNavItemText {
  color: #ffffff;
  font-size: 28rpx;
}

.video {
  width: 100%;
  height: 100%;
  overflow: hidden;
  .swiper {
    height: calc(100% - 90rpx);
  }
  .live {
    height: 100%;
    // 直播列表导航条
    .liveNav {
      height: 70upx;
      white-space: nowrap;
      background-color: #000000;
      &-item {
        line-height: 70upx;
        padding: 0 30upx;
        display: inline-block;
        text {
          font-size: 28upx;
          color: #6db7ed;
        }
        &.active {
          background-color: #fa8fc6;
          border-radius: 12upx;
          color: #ffffff;
          transform: scale(0.78);
          font-size: 32upx;
          text {
            color: #ffffff;
            transform: scale(1.1);
            display: inline-block;
          }
        }
      }
    }
    // 视频播放器
    .videoPlayer {
      width: 100%;
      height: 400upx;
      // background-color: #000000;
      // position: relative;
    }
  }
}

#video{
  width: 750rpx;
  height: 400rpx;
}
</style>
